import React, { useEffect, useState } from 'react';
import { Descriptions, Table, Modal, Divider, Button, Popconfirm } from 'antd'
import {
  settleOrCancelSettle,
  getOnceOrderDetail,
  getSettleDetail,
  getSettleDetailGoodsList,
  getPlanOrderDetail
} from '@/services/order/api';
import { OrderStatus } from '@/utils/constants';
// @ts-ignore
import QRCode from 'qrcode.react';
import { showMsg, print } from '@/utils/utils';
import { SettStatus } from '@/utils/constants';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import PermissionControl from '@/components/PermissionControl';

const OrderDetail: React.FC<any> = (props) => {
  const {
    title = '查看订单',
    type,
    record = {},
    handleModalVisible,
    order_id,
    optCallback,
    isPrint = false, // 是否进入页面就打印
    cancelOrder
  } = props;

  const [payLoading, setPayLoading] = useState<boolean>(false);
  const [printing, setPrinting] = useState(false);// 是否弹出打印窗口

  const columns: any[] = [
    {
      title: '分类',
      dataIndex: 'class_name'
    },
    {
      title: '品牌',
      dataIndex: 'brand_name'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id'
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name'
    },
    {
      title: '单价',
      dataIndex: 'goods_price'
    },
    {
      title: '数量',
      dataIndex: 'goods_num'
    },
    {
      title: '原价',
      dataIndex: 'goods_price'
    },
    {
      title: '折扣',
      dataIndex: 'discount'
    },
    {
      title: '折扣价',
      dataIndex: 'discount_price'
    }
  ]

  const columns2: any[] = [
    {
      title: '品牌',
      dataIndex: 'brand_name'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id'
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name'
    },
    {
      title: '原折扣',
      dataIndex: 'goods_price'
    },
    {
      title: '数量',
      dataIndex: 'goods_num'
    },

    {
      title: '折扣价',
      dataIndex: 'discount_price'
    },
    {
      title: '退款数量',
      dataIndex: 'discount_price'
    },
    {
      title: '退款金额',
      dataIndex: 'discount_price'
    }
  ]

  const settColumns: ProColumns<any>[] = [
    {
      title: '账单日期',
      dataIndex: 'bill_date'
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      width: 150
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 150
    },

    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      render: (_, entity) => {
        return `${entity.specs_name}(${entity.unit})`;
      }
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right'
    },
    {
      title: '用量',
      dataIndex: 'bill_num',
      align: 'right',
      render: (_, entity) => {
        return entity.check_num > -1 ? entity.check_num : entity.bill_num;
      }
    },
    {
      title: '账单费用',
      dataIndex: 'bill_price',
      valueType: 'money',
      align: 'right'
    }
  ]
  const [detail, setDetail] = useState<any>({});
  const [showQrCode, setShowQrCode] = useState(false);

  // 订单详情
  const [onceOrderDetail, setOnceOrderDetail] = useState<ORDERAPI.OnceOrderItem>({});

  const [planOrderDetail, setPlanOrderDetail] = useState<any>({});

  // 商品数量
  const [goodsNum, setGoodsNum] = useState<number>(0)

  // 一次性订单详情
  const fetchOnceOrderDetail = async () => {
    try {
      const data = await getOnceOrderDetail(record.order_id);
      setOnceOrderDetail(data);
      const tmp = Object.assign(data, detail);
      setDetail(tmp);
      // 是否显示付款码
      setShowQrCode(type && tmp.sett_status === 'G' && tmp.pay_qr_code_url);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 计划订单详情
  const fetchPlanOrderDetail = async () => {
    try {
      const data = getPlanOrderDetail(order_id);
      setPlanOrderDetail(data);
      return data;
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 获取结算详情
  const fetchSettleDetail = async () => {
    try {
      const data = await getSettleDetail({
        order_id,
        sett_id: record.sett_id
      })
      return data;
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 计划订单结算信息
  const getPlanOrderSettleDetail = (readyPrint?: Boolean) => {
    fetchPlanOrderDetail().then(planDetail => {
      fetchSettleDetail().then((sd: any) => {
        getSettleDetailGoodsList({
          order_id,
          sett_id: record.sett_id,
          current: 1,
          pageSize: 9999999
        }).then(res => {
          let goodsNum = 0;
          let list = res.record_list;
          list.map(item => {
            goodsNum += (item.check_num > -1 ? item.check_num : item.bill_num);
          });
          setGoodsNum(goodsNum);
          const tmp = Object.assign({}, planDetail, sd, { order_goods_list: res.record_list });
          setDetail(tmp);
          // 是否显示付款码
          setShowQrCode(type && tmp.sett_status === 'G' && tmp.pay_qr_code_url);
          if (readyPrint) {
            printPage();
          }
        })
      })
    })
  }

  useEffect(() => {
    // 一次性订单
    if (record.order_id) {
      fetchOnceOrderDetail();
    }

    // 计划订单结算详情
    if (type === 'settleInfo') {
      getPlanOrderSettleDetail(isPrint);
    }
  }, [order_id, type]);

  const printPage = () => {
    setPrinting(true);
    setTimeout(() => {
      print(document.querySelector('.order-detail-modal .ant-modal-body'), {
        size: 'portrait'
      });
      setTimeout(() => {
        setPrinting(false);
      }, 5000);
    }, 500);
  }

  return <Modal
    title={title}
    maskClosable={false}
    width="90%"
    bodyStyle={{ height: window.innerHeight - 185, overflowY: 'auto' }}
    className="order-detail-modal"
    onCancel={() => handleModalVisible(false)}
    footer={[
      <Button key="back" onClick={() => {
        handleModalVisible(false);
      }}>
        关闭
      </Button>,
      ['U', 'G'].includes(detail.sett_status) ?
      <PermissionControl key="cancel" action_id="400401019">
        <Popconfirm 
          placement="topRight"
          key="cancel"
          title={record.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : ''}
          onConfirm={cancelOrder}
          okText="确认取消"
          disabled={record.manager_flag !== 'Y'}
          cancelText="再想想">
            <Button style={{ marginLeft: 10 }} onClick={() => {
              if (record.manager_flag !== 'Y') {
                cancelOrder();
              }
            }}>取消</Button>
        </Popconfirm>
      </PermissionControl> : null,
      // eslint-disable-next-line no-nested-ternary
      !type && ['C', 'W'].includes(detail.order_status as string) ?
        <Button key="pay" loading={payLoading} type="primary" onClick={() => { alert('这里没调用？') }}>
          发起支付
        </Button> : ['U'].includes(detail.sett_status) && detail.manager_flag !== 'Y' ? <Button
          loading={payLoading}
          key="pay"
          type="primary"
          style={{ marginLeft: 10 }}
          onClick={async () => {
            try {
              if (payLoading) {
                return;
              }
              setPayLoading(true);
              await settleOrCancelSettle({
                order_id,
                sett_id: record.sett_id,
                sett_status: 'G'
              })
              setPayLoading(false);
              const data = await getSettleDetail({
                order_id,
                sett_id: record.sett_id
              });
              optCallback?.(data);
            } catch (error) {
              showMsg(error?.data?.errmsg);
              setPayLoading(false);
            }
          }}>
          发起支付
        </Button> : null,

      type && ['G'].includes(detail.sett_status) ? <Button
        key="refresh"
        type="primary"
        style={{ marginLeft: 10 }}
        onClick={() => {
          getPlanOrderSettleDetail();
        }}
      >刷新</Button> : null,
      ['G', 'P'].includes(detail.sett_status) ?
      <Button key="print" type="primary" onClick={printPage}>
        打印结算单
      </Button> : null
    ]}
    visible>
    <div className="dialog">
      <div className='print_yes print_title' style={{ display: 'none' }}>缴费单</div>
      <Divider className='print_yes' style={{ paddingBottom: 15, display: 'none' }} />
      <div className='common_title'>1.患者信息</div>
      <Divider style={{ margin: '10px 0' }} />
      <div style={{ display: 'flex' }}>
        <Descriptions column={printing ? 1 : 3}>
          <Descriptions.Item label="身份证/住院号" span={printing ? 2 : 1}>
            {detail.identity_no}{detail.identity_no && detail.admission_num ? ' / ' : ''}{detail.admission_num}
          </Descriptions.Item>
          <Descriptions.Item label="患者姓名">{detail.patient_name}</Descriptions.Item>
          <Descriptions.Item label="归属科室">{detail.patient_dept_name || detail.patient_dept_code}</Descriptions.Item>
        </Descriptions>
        {
          (showQrCode && printing) && <Descriptions.Item>
            <Descriptions className='print_ewm'>
              <Descriptions.Item label="付款码">
                <QRCode
                  // value参数为生成二维码的链接
                  value={detail.pay_qr_code_url}
                  // 二维码的宽高尺寸
                  size={120}
                  // 二维码的颜色
                  fgColor="#000"
                  renderAs="svg"
                />
              </Descriptions.Item>
            </Descriptions>
          </Descriptions.Item>
        }
      </div>
      <div className='common_title' style={{ marginTop: 15 }}>2.商品信息</div>
      <Divider style={{ margin: '10px 0 0' }} />
      <ProTable<any>
        className='print_table'
        // style={{ marginTop: -10 }}
        rowKey={type === 'settleInfo' ? 'bill_id' : 'goods_id'}
        columns={type === 'settleInfo' ? settColumns : columns}
        scroll={{ x: 1000 }}
        options={false}
        search={false}
        dataSource={detail.order_goods_list}
        pagination={false}
        bordered />

      <div className='common_title' style={{ marginTop: 15 }}>3.结算信息</div>
      <Divider style={{ margin: '10px 0' }} />
      <Descriptions column={showQrCode ? 5 : 3}>
        <Descriptions.Item span={showQrCode ? 4 : 3} className='noBottom'>
          <Descriptions column={showQrCode ? 2 : 3}>
            <Descriptions.Item label="订单编号">{order_id}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{detail.create_date + ' ' + detail.create_time}</Descriptions.Item>
            {
              detail.pay_time && <Descriptions.Item span={2} label="支付时间">{detail.pay_time}</Descriptions.Item>
            }
            {
              detail.goods_total_price && <Descriptions.Item label="商品原价">{detail.goods_total_price}</Descriptions.Item>
            }
            <Descriptions.Item label="商品数量">
              <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{goodsNum}（件）</span>
            </Descriptions.Item>
            {
              // !type ? <Descriptions.Item label="订单金额">
              //   <div><span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.total_price}</span>（元）{detail.manager_flag === 'Y' && '(通过出院办结合并支付)'}</div>
              // </Descriptions.Item> :
              // <Descriptions.Item label="总价">
              //   <div><span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.total_bill_price}</span>（元）{detail.manager_flag === 'Y' && '(通过出院办结合并支付)'}</div>
              // </Descriptions.Item>
              <Descriptions.Item label="订单金额">
                <div><span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.total_price || detail.total_bill_price}</span>（元）{detail.manager_flag === 'Y' && '(通过出院办结合并支付)'}</div>
              </Descriptions.Item>
            }

            {
              (detail.discount_ratio || detail.discount) && <Descriptions.Item label="订单折扣">
                <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.discount_ratio || detail.discount}</span>
              </Descriptions.Item>
            }

            {
              detail.sett_price && <Descriptions.Item label="结算价格">
                <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.sett_price}</span>（元）
              </Descriptions.Item>
            }
            {
              detail.sett_no && <Descriptions.Item label="结算单号" className='print_no'>{detail.sett_no}</Descriptions.Item>
            }
            {
              detail.remarks && <Descriptions.Item label="订单备注" className='print_no'>{detail.remarks}</Descriptions.Item>
            }
            {printing && detail.create_dept_code === '11232300' && <Descriptions.Item label="取货地址">生活服务楼三楼314号房</Descriptions.Item>}
          </Descriptions>
        </Descriptions.Item>
        {
          (showQrCode && !printing) && <Descriptions.Item>
            <Descriptions column={1}>
              <Descriptions.Item label="付款码">
                <QRCode
                  // value参数为生成二维码的链接
                  value={detail.pay_qr_code_url}
                  // 二维码的宽高尺寸
                  size={120}
                  // 二维码的颜色
                  fgColor="#000"
                  renderAs="svg"
                />
              </Descriptions.Item>
            </Descriptions>
          </Descriptions.Item>
        }
      </Descriptions>
      {
        detail.order_status === 'E' && <React.Fragment>
          <div className='common_title' style={{ marginBottom: 10 }}>4.退款信息</div>
          <Table
            rowKey="goods_id"
            columns={columns2}
            scroll={{ x: 1000 }}
            dataSource={detail.order_goods_list}
            bordered />
          <Descriptions column={4}>
            <Descriptions.Item label="退款单号">{detail.create_user_name}</Descriptions.Item>
            <Descriptions.Item label="退款时间">{detail.modify_user_name}</Descriptions.Item>
            <Descriptions.Item label="退款数量">{detail.order_person}</Descriptions.Item>
            <Descriptions.Item label="退款总额">{OrderStatus[detail.order_status as string]}</Descriptions.Item>
          </Descriptions>
        </React.Fragment>
      }

      <Divider style={{ margin: '10px 0' }} />
      <Descriptions column={4}>
        <Descriptions.Item label="订单创建人">{detail.create_user_name}</Descriptions.Item>
        <Descriptions.Item label="订单修改人">{detail.modify_user_name || '无'}</Descriptions.Item>
        {
          !type && <Descriptions.Item label="订单责任人">{detail.order_person}</Descriptions.Item>
        }
        <Descriptions.Item label="订单状态">
          <span style={{ color: '#1F1F1F', fontWeight: 'bold' }}>
            {type ? SettStatus[detail.sett_status] : OrderStatus[detail.order_status as string]}
          </span>
        </Descriptions.Item>
      </Descriptions>
    </div>
  </Modal>
}

export default OrderDetail;
